import { FC, useEffect, useMemo, useState } from "react";
import { Card } from "antd-mobile";
import { UpOutline, DownOutline } from "antd-mobile-icons";
import classNames from "classnames";
import styled from "./question.module.scss";

type Props = {
  // 问题对象
  q: API.Iq;
  // 选择的答案Id集合
  a: string[] | undefined;
  // 设置答案
  setA: (answers: string[]) => void;
};

const Extra = ({ collapsed, name }: { collapsed: boolean; name: string }) => {
  return (
    <div
      style={{
        width: "50%",
        display: "flex",
        justifyContent: "flex-end",
        alignItems: "center",
        whiteSpace: "nowrap",
        overflow: "hidden",
        textOverflow: "ellipsis",
      }}
    >
      <span>{name}</span>
      {collapsed ? <UpOutline fontSize={24} /> : <DownOutline fontSize={24} />}
    </div>
  );
};

const Question: FC<Props> = ({ q, a, setA }) => {
  // 题目类型，single - 单选 multiple - 多选
  const type = q.id === "0" ? "multiple" : "single";

  // 是否收起
  const [collapsed, setCollapsed] = useState(false);

  // 当前选择的答案
  const title = useMemo(() => {
    return q.question
      .filter((item) => a?.includes(item.id))
      .map((item) => item.name)
      .join(" ");
  }, [q, a]);

  // 监听答案
  useEffect(() => {
    // 选择答案之后自动收起
    if (a && type !== "multiple") {
      setCollapsed(true);
    } else {
      setCollapsed(false);
    }
  }, [a, type]);

  // 卡片头部点击
  const handleHeaderClick = () => {
    // 得作答之后才可以操作
    if (a?.length && type !== "multiple") {
      // 对 collapsed 取反
      setCollapsed(!collapsed);
    }
  };

  // 答案点击
  const handleClick = (data: API.Ia) => {
    console.log(data);

    if (type === "single") {
      // 单选
      setA([data.id]);
    } else {
      // 多选
      let newA = a ? [...a] : [];
      if (newA.includes(data.id)) {
        newA = newA.filter((item) => item !== data.id);
      } else {
        newA.push(data.id);
      }
      setA(newA);
    }
  };

  return (
    <Card
      title={q.name}
      extra={<Extra collapsed={collapsed} name={title} />}
      onHeaderClick={handleHeaderClick}
    >
      {!collapsed && (
        <div className={classNames([styled.answers, type])}>
          {q.question.map((item) => (
            <div
              key={item.id}
              className={classNames([
                styled.item,
                {
                  [styled.active]: a?.includes(item.id),
                },
              ])}
              onClick={() => handleClick(item)}
            >
              {item.name}
            </div>
          ))}
        </div>
      )}
    </Card>
  );
};

export default Question;
